package com.ilovepostcard.controller;

import android.app.ProgressDialog;
import android.content.Context;
import android.widget.Toast;

import com.ilovepostcard.R;
import com.ilovepostcard.controller.server.PostcardResult;
import com.ilovepostcard.utils.StringUtils;

public abstract class ServerAsyncTask extends BaseAsyncTask {

    PostcardResult result;
    ProgressDialog pd;
    protected Context context;
    boolean dialogFalg;
    
    public ServerAsyncTask(Context context) {
        super();
        this.context = context;
    }
    
    public ServerAsyncTask(Context context , boolean flag) {
    	this(context);
    	showDialog(flag);
    }

    @Override
    protected void _onPreExecute() {
        if (isShowDialog()) {
            pd = new ProgressDialog(context);
            pd.setMessage(getLoadingMessage());
            pd.show();
        }
    }
    
    protected String getLoadingMessage() {
        return context.getString(R.string.loading_data);
    }
    
    public void showDialog(boolean flag)
    {
    	dialogFalg = flag;
    }
    protected boolean isShowDialog() {
        return dialogFalg;
    }
    
    @Override
    protected void _doInBackground() {
        result = doRequest();
    }

    @Override
    protected void _onPostExecute() {
        if (pd != null) {
            try {
                pd.dismiss();
            } catch (Exception e) {

            }
        }
        if (result != null && result.isSuccess()) {
            onSuccess(result);
        } else {
            if (result != null) {
                String error = result.getErrorMsg(context);
                if (StringUtils.isNotEmpty(error))
                    Toast.makeText(context, error, Toast.LENGTH_SHORT).show();
            }
        }
    }
    
    protected abstract PostcardResult doRequest();
    
    protected abstract void onSuccess(PostcardResult result);

}
